﻿import mx.utils.Delegate;

import com.mixmedia.mx.AbstractEventDispatcher;
import com.mixmedia.mx.events.LoaderEvent;
import com.mixmedia.net.ILoadStrategy;
import com.mixmedia.mx.NetStreamEvt;

/**
 * @author Colin
 */
class com.mixmedia.net.LoadFLV extends AbstractEventDispatcher implements ILoadStrategy {
	private var vid : Video;
	private var vid_nc : NetConnection;
	private var vid_ns : NetStreamEvt;
	private var buffer :Number=0;

	private var iid:Number;

	private var isOpen : Boolean;
	private var isComplete : Boolean;
	private var isReady : Boolean;

	public function LoadFLV(vid:Video,deblocking:Number,smooth:Boolean,buffer:Number){
		this.vid = vid;
		vid.deblocking = (deblocking==null)?2:deblocking;
		vid.smoothing = (smooth==null)?true:smooth;
		this.buffer = (buffer==null)?0:buffer;
	}

	public function load(requestURL:String):Void{
		//release netConnection and NetStream, flash cannot auto release it.
		kill();

		//setup netstream
		vid_nc = new NetConnection();
		vid_nc.connect(null);

		vid_ns = new NetStreamEvt(vid_nc);
		vid_ns.setBufferTime(buffer);
		vid_ns.onStatus = Delegate.create(this,onStreamStatus);
		vid_ns.addEventListener(LoaderEvent.EVENTOPEN,Delegate.create(this,onMetaData));

		vid.attachVideo(vid_ns);

		vid_ns.play(requestURL);
		vid_ns.pause(true);
		
		isOpen = false;
		isComplete=false;
		isReady = false;
		clearInterval(iid);
		iid = setInterval(Delegate.create(this,checkStatus),250);
	}

	private function checkStatus(){
		if(vid_ns.bytesTotal>0 && isOpen!=true){
			dispatchEvent(new LoaderEvent(this,LoaderEvent.EVENTOPEN,vid_ns));
			dispatchEvent(new LoaderEvent(this,LoaderEvent.EVENTREADY,vid_ns));
			isOpen = true;
		}
		
		if(vid_ns.bytesLoaded>=vid_ns.bytesTotal && isComplete!=true){
			dispatchEvent(new LoaderEvent(this,LoaderEvent.EVENTCOMPLETE,vid_ns));
			isComplete = true;
			clearInterval(iid);
		}

		dispatchEvent(new LoaderEvent(this,LoaderEvent.EVENTPROGRESS,vid_ns));
	}

	private function kill(){
		if(vid_nc!=null)vid_nc.close();
		if(vid_ns!=null)vid_ns.close();
		delete vid_nc;
		delete vid_ns;
	}

	public function getTarget() : Object {
		return vid_ns;
	}

	private function onStreamStatus(evt){
		if(evt.code=="NetStream.Play.StreamNotFound"){
			dispatchEvent(new LoaderEvent(this,LoaderEvent.EVENTERROR,vid_ns,"NetStream.Play.StreamNotFound"));
		}
	}

	private function onMetaData(evt:Object) : Void {
		dispatchEvent(new LoaderEvent(this,LoaderEvent.EVENTOPEN,vid_ns));
	}
}